/*
 * LEDC1.c
 *
 *  Created on: 17/11/2012
 *      Author: Richard
 */

#include "LEDC1.h"
#include "../../../Driver/DIO/DIOC1.h"
#include "../../SWTIMER/SWTIMERC1.h"

void _LED__vTimerCallback( SWTIM_tstTimer *pstTimer );
void _LED__vTimerTimeoutCallback( SWTIM_tstTimer *pstTimer );

static LED_tenOutputType LED__enCurrentFunction;
static SWTIM_tstTimer LED__stFlashTimer;
static SWTIM_tstTimer LED__stTimeoutTimer;

static void LED__vDisplayWaterLevel( void )
{
	volatile uint8 u8WaterLevel = 80;
	/* obtain water level as a percentage */
	//u8WaterLevel = WTR_u8GetLevel();

	/* set timeout for LED's - 10 seconds */
   LED__stTimeoutTimer.interval = 10000;
   SWTIM_vTimerStart( &LED__stTimeoutTimer );

	DIO_vSetOutput( DIO_nenLED_Bar_1, tLo );
	DIO_vSetOutput( DIO_nenLED_Bar_2, tLo );

	if( u8WaterLevel > 25 )
	{
		DIO_vSetOutput( DIO_nenLED_Bar_1, tHi );
	}
	if( u8WaterLevel > 75 )
	{
		DIO_vSetOutput( DIO_nenLED_Bar_2, tHi );
	}
}

static void LED__vDisplayFlash( void )
{
   LED__stTimeoutTimer.interval = 30000;
   SWTIM_vTimerStart( &LED__stTimeoutTimer );

	switch( LED__enCurrentFunction )
	{
		case LED_nenFlash:
			LED__stFlashTimer.interval = 500;
			break;
		case LED_nenFlashFast:
		   LED__stFlashTimer.interval = 250;
			break;
		default:
			break;
	}

   SWTIM_vTimerStart( &LED__stFlashTimer );

	DIO_vSetOutput( DIO_nenLED_Bar_1, tHi );
}

static void LED__vDisplayOff( void )
{
	DIO_vSetOutput( DIO_nenLED_Bar_1, tLo );
	DIO_vSetOutput( DIO_nenLED_Bar_2, tLo );

	if( SWTIM_boTimerStarted( &LED__stFlashTimer ) == True )
	{
	   SWTIM_vTimerStop( &LED__stFlashTimer );
	}

   if( SWTIM_boTimerStarted( &LED__stTimeoutTimer ) == True )
   {
      SWTIM_vTimerStop( &LED__stTimeoutTimer );
   }
}

void _LED__vTimerCallback( SWTIM_tstTimer *pstTimer )
{
   (void)pstTimer;
   DIO_vToggleOutput( DIO_nenLED_Bar_1 );
}

void _LED__vTimerTimeoutCallback( SWTIM_tstTimer *pstTimer )
{
   (void)pstTimer;
   LED_vSetOutput( LED_nenOff );
}

void LED_vReset( void )
{
   LED__stTimeoutTimer.mode = SWTIM_nenOneShotMode;
   LED__stTimeoutTimer.handler = &_LED__vTimerTimeoutCallback;

   LED__stFlashTimer.mode = SWTIM_nenPeriodicMode;
   LED__stFlashTimer.handler = &_LED__vTimerCallback;

	LED__enCurrentFunction = LED_nenOff;
}

void LED_vSetOutput( LED_tenOutputType enOutput )
{
	LED__vDisplayOff();
	LED__enCurrentFunction = enOutput;

	switch( enOutput )
	{
		case LED_nenWaterLevel:
			LED__vDisplayWaterLevel();
			break;
		case LED_nenFlash:
			LED__vDisplayFlash();
			break;
		case LED_nenFlashFast:
			LED__vDisplayFlash();
			break;
		case LED_nenOff:
		default:
			break;
	}
}

LED_tenOutputType LED_enGetCurrentOperation( void )
{
	return LED__enCurrentFunction;
}
